package view.listeners;

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import model.Constants;
import model.HostAddress;
import model.Octet;
import view.components.HostComboBox;
import view.views.dialogContentViews.SubnetBoxPanel;
import controller.Calculator;
import controller.Controller;

public class HostBoxListener implements ItemListener {

	private final HostComboBox hostBox;
	private final SubnetBoxPanel subnetBoxPanel;

	public HostBoxListener(HostComboBox hostBox, SubnetBoxPanel subnetBoxPanel) {
		this.hostBox = hostBox;
		this.subnetBoxPanel = subnetBoxPanel;

	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		
			if (!hostBox.getBox().getSelectedItem()
						.equals(Constants.EMPTY)) {
				HostAddress host = hostBox.getHostMap().get(
						hostBox.getBox().getSelectedItem());
				Controller.getInstance().setCurrentHost(host);

				if (!host.getSubnetList().isEmpty()) {

					Octet[] startAddress = host.getSubnetList()
							.get(host.getSubnetList().size() - 1)
							.getBroadcastAddress().getAddressBits();

					int firstBit = startAddress[0].getBitValue();
					int secondBit = startAddress[1].getBitValue();
					int thirdBit = startAddress[2].getBitValue();
					int fourthBit = startAddress[3].getBitValue() + 1;


					if (fourthBit > 255) {
						fourthBit = 0;
						thirdBit++;
						if (thirdBit > 255) {
							thirdBit = 0;
							secondBit++;
							if (secondBit > 255) {
								secondBit = 0;
								firstBit++;
							}
						}
					}

					Calculator.getInstance().modifyIpTextArea(firstBit,
							secondBit, thirdBit, fourthBit, subnetBoxPanel);

				} else {
					int firstBit = host.getHostAddress().getAddressBits(0)
							.getBitValue();
					int secondBit = host.getHostAddress().getAddressBits(1)
							.getBitValue();
					int thirdBit = host.getHostAddress().getAddressBits(2)
							.getBitValue();
					int fourthBit = host.getHostAddress().getAddressBits(3)
							.getBitValue() + 1;

					if (fourthBit > 255) {
						fourthBit = 0;
						thirdBit++;
						if (thirdBit > 255) {
							thirdBit = 0;
							secondBit++;
							if (secondBit > 255) {
								secondBit = 0;
								firstBit++;
							}
						}
					}

					Calculator.getInstance().modifyIpTextArea(firstBit,
							secondBit, thirdBit, fourthBit, subnetBoxPanel);

				}



		}

	}

}
